package com.lekang.system.controller;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.lekang.common.core.controller.BaseController;
import com.lekang.common.core.domain.AjaxResult;
import com.lekang.system.service.IBillService;
import com.lekang.system.service.ICheckInManagementService;
import com.lekang.system.task.BillGenerationTask;

/**
 * 账单定时器测试Controller
 * 
 * @author lekang
 * @date 2025-10-24
 */
@RestController
@RequestMapping("/system/bill-timer-test")
public class BillTimerTestController extends BaseController
{
    @Autowired
    private BillGenerationTask billGenerationTask;
    
    @Autowired
    private IBillService billService;
    
    @Autowired
    private ICheckInManagementService checkInManagementService;

    /**
     * 手动触发月度账单生成
     */
    @PreAuthorize("@ss.hasPermi('system:bill:list')")
    @GetMapping("/trigger-generate-monthly-bills")
    public AjaxResult triggerGenerateMonthlyBills() {
        try {
            billGenerationTask.manualGenerateBills();
            
            Map<String, Object> result = new HashMap<>();
            result.put("message", "月度账单生成任务已触发");
            result.put("triggerTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            result.put("nextMonth", java.time.YearMonth.now().plusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM")));
            
            return success("月度账单生成任务已触发").put("data", result);
        } catch (Exception e) {
            System.err.println("手动触发月度账单生成失败: " + e.getMessage());
            e.printStackTrace();
            return error("触发失败：" + e.getMessage());
        }
    }

    /**
     * 手动触发欠费账单标记
     */
    @PreAuthorize("@ss.hasPermi('system:bill:list')")
    @GetMapping("/trigger-mark-overdue-bills")
    public AjaxResult triggerMarkOverdueBills() {
        try {
            billGenerationTask.manualMarkOverdue();
            
            Map<String, Object> result = new HashMap<>();
            result.put("message", "欠费账单标记任务已触发");
            result.put("triggerTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            
            return success("欠费账单标记任务已触发").put("data", result);
        } catch (Exception e) {
            System.err.println("手动触发欠费账单标记失败: " + e.getMessage());
            e.printStackTrace();
            return error("触发失败：" + e.getMessage());
        }
    }

    /**
     * 获取已入住老人数量（用于测试）
     */
    @PreAuthorize("@ss.hasPermi('system:bill:list')")
    @GetMapping("/elderly-count")
    public AjaxResult getElderlyCount() {
        try {
            int elderlyCount = billService.getElderlyCountForBillGeneration();
            
            Map<String, Object> result = new HashMap<>();
            result.put("elderlyCount", elderlyCount);
            result.put("message", "已入住老人数量：" + elderlyCount);
            
            return success("获取成功").put("data", result);
        } catch (Exception e) {
            System.err.println("获取已入住老人数量失败: " + e.getMessage());
            e.printStackTrace();
            return error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 获取指定月份已存在的账单数量
     */
    @PreAuthorize("@ss.hasPermi('system:bill:list')")
    @GetMapping("/existing-bill-count")
    public AjaxResult getExistingBillCount(@RequestParam String billMonth) {
        try {
            int existingBillCount = billService.getExistingBillCount(billMonth);
            
            Map<String, Object> result = new HashMap<>();
            result.put("billMonth", billMonth);
            result.put("existingBillCount", existingBillCount);
            result.put("message", billMonth + " 月份已存在账单数量：" + existingBillCount);
            
            return success("获取成功").put("data", result);
        } catch (Exception e) {
            System.err.println("获取已存在账单数量失败: " + e.getMessage());
            e.printStackTrace();
            return error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 测试账单生成统计
     */
    @PreAuthorize("@ss.hasPermi('system:bill:list')")
    @GetMapping("/test-bill-generation")
    public AjaxResult testBillGeneration() {
        try {
            // 获取已入住老人数量
            int elderlyCount = billService.getElderlyCountForBillGeneration();
            
            // 获取下个月
            String nextMonth = java.time.YearMonth.now().plusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM"));
            
            // 获取下个月已存在的账单数量
            int existingBillCount = billService.getExistingBillCount(nextMonth);
            
            Map<String, Object> result = new HashMap<>();
            result.put("elderlyCount", elderlyCount);
            result.put("existingBillCount", existingBillCount);
            result.put("willGenerateCount", elderlyCount - existingBillCount);
            result.put("testTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            
            return success("账单生成测试完成").put("data", result);
        } catch (Exception e) {
            System.err.println("测试账单生成失败: " + e.getMessage());
            e.printStackTrace();
            return error("测试失败：" + e.getMessage());
        }
    }
}
